<template>
    <div class="box-body no-padding">
        <div class="mailbox-controls with-border">
            <div class="btn-group">
                <a href="" @click.prevent="handleRefresh" type="button"
                   class="btn btn-default btn media-reload" title="Refresh">
                    <i class="fa fa-refresh"></i>
                </a>
                <a type="button"
                   v-if="canDelete"
                   class="btn btn-default btn file-delete-multiple"
                   title="Delete"
                   @click.prevent="handleMultipleDelete">
                    <i class="fa fa-trash-o"></i>
                </a>
            </div>
            <label v-if="canUpload" @click="handleOpenUpload" class="btn btn-default btn">
                <i class="fa fa-upload"></i>&nbsp;&nbsp;上传
            </label>

            <!-- /.btn-group -->
            <a class="btn btn-default btn"
               v-if="canUpload"
               @click="handleMakeFolder">
                <i class="fa fa-folder"></i>&nbsp;&nbsp;新建文件夹
            </a>

            <div class="btn-group">
                <a :class=" view === 'table' && 'active'"
                   @click.prevent="setView('table')"
                   class="btn btn-default ">
                    <i class="fa fa-list"></i>
                </a>
                <a :class=" view === 'list' && 'active'"
                   @click.prevent="setView('list')"
                   class="btn btn-default ">
                    <i class="fa fa-th"></i>
                </a>
            </div>

            <div v-if="false" class="input-group input-group-sm pull-right goto-url" style="width: 250px;">
                <input type="text" name="path" class="form-control pull-right"
                       v-mode="searchInput">
                <div class="input-group-btn">
                    <button type="submit" class="btn btn-default"><i class="fa fa-arrow-right"></i>
                    </button>
                </div>
            </div>

        </div>
        <el-dialog title="上传文件"
                   width="30%"
                   :before-close="handleUploadClose"
                   :visible.sync="uploadDialog">
            <div>
                <el-upload
                        class="upload-demo"
                        action="https://jsonplaceholder.typicode.com/posts/"
                        multiple
                        :before-upload="beforeUpload"
                        :http-request="handleUploadFile"
                        :file-list="fileList">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">上传文件不要太大</div>
                </el-upload>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import axios from 'axios';

    export default {
        name   : "media-nav-bar",
        props  : [ 'list', 'permissions', 'path', 'view', 'canDelete', 'canUpload', 'canEdit' ],
        data() {
            return {
                uploadDialog : false,
                successUpload: false,
                fileList     : [],
                searchInput  : '',

            };
        },
        methods: {
            setView(val) {
                this.$emit('changeView', val);
            },
            handleMakeFolder() {
                this.$prompt('创建文件夹', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText : '取消',
                    inputPattern     : /^[^\\\\\\/:*?\\"<>|]+$/,
                    inputErrorMessage: '文件名格式不正确',
                    beforeClose      : async (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true;
                            instance.closeOnClickModal    = false;
                            instance.confirmButtonText    = '光速创建中...';
                            let value                     = instance.inputValue;


                            let res                       = await axios({
                                method: 'post',
                                url   : '/api/media/makeFolder',
                                data  : {
                                    dir : this.path,
                                    name: value,
                                }
                            });
                            instance.confirmButtonLoading = false;
                            instance.closeOnClickModal    = true;
                            console.log('res :', res);
                            if (res.status === 204) {
                                this.$message.success('创建文件夹成功.');
                                this.$emit('mapLoadList');

                            } else {
                                this.$message.warning('创建失败,请联系管理员.');
                            }


                        }
                        console.log('action :', action);
                        console.log('instance :', instance);
                        done();

                    }
                });

            },
            handleRefresh() {
                this.$emit('mapLoadList');
            },
            handleMultipleDelete() {
                let files = $(".file-select input:checked")
                    .map((_, el) => $(el).val())
                    .toArray();
                this.$emit('deleteFile', files);
            },
            handleOpenUpload() {
                this.uploadDialog  = true;
                this.successUpload = false;
            },
            handleUploadClose(done) {
                if (this.successUpload) {
                    this.$emit('mapLoadList');
                }
                this.successUpload = false;
                done();
            },
            beforeUpload(file) {
                console.log('beforeUpload file :', file);
                let fileExists = this.checkFileIsExists(file);

                if (fileExists) {
                    return this.$confirm('已有相同文件名的文件存在, 是否覆盖?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText : '取消',
                        type             : 'warning'
                    })
                }
                console.log('fileExists :', fileExists);
            },
            handleUploadFile(item) {
                console.log('file :', item);

                let formData = new FormData();
                formData.append('files', item.file);
                formData.append('dir', this.path);

                axios({
                    method: 'post',
                    url   : '/api/media/upload',
                    data  : formData,
                }).then((res) => {
                    console.log('res :', res);
                    item.onSuccess(res);
                    this.$message.success('文件上成功');
                    !this.successUpload && (this.successUpload = true);
                }).catch((e) => {
                    item.onError(e);
                    this.$message.error('上传失败，请重新上传')
                    console.log('报错', e);
                })
            },
            checkFileIsExists(file) {
                let res = this.list.findIndex((item) => {
                    return item.basename === file.name;
                });

                let index = this.fileList.findIndex((item) => {
                    return item.name !== file.name
                });

                return res === -1 ? index !== -1 : true;

            },
        },
    }
</script>

<style scoped lang="less">

</style>
